/**
 * 
 */
package com.maywide.jdp.system.spring;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.View;

import com.maywide.jdp.system.servlet.HttpHead;
import com.maywide.jdp.system.utils.JSONUtils;

/**
 * @author Administrator
 */
@Component("jsonView")
public class JSONView implements View,BeanNameAware {
	public static String VIEW_NAME = "jsonView";
	
	private String encoding = "UTF-8";
	
	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	@Override
	public void setBeanName(String name) {
		VIEW_NAME = name;
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.View#getContentType()
	 */
	@Override
	public String getContentType() {
		return HttpHead.CONTENT_TYPE_JSON;
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.View#render(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void render(Map<String, ?> model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if(model == null || model.isEmpty())
			return;
		
		Object object = model;
		if(request.getAttribute("isMapObject") == null)
			object = model.entrySet().iterator().next().getValue();
		String json = JSONUtils.toJson(object);
		response.addHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
		response.addDateHeader("Expires", 1L);
		response.setContentType(getContentType());
		response.setCharacterEncoding(encoding);
		PrintWriter write = response.getWriter();
		write.write(json);
		write.flush();
	}

}
